package com.zixue.heima.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @ClassName : SeverSelectorDemo
 * @Description : TODO
 * @Author : chunxiong
 * @Date : 2025/4/17 22:40
 * @Version 1.0
 */
public class SeverSelectorDemo {
    public static void main(String[] args) throws IOException {
        //1。创建selector;  //可以管理多个channel
        Selector selector = Selector.open();

        ByteBuffer byteBuffer = ByteBuffer.allocate(12);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(9090));

        //难怪我selector点不出来， 原来用channel调用方法
        //selectionKey事件发生
        SelectionKey selectionKey = serverSocketChannel.register(selector, 0, null);//0就是不关注任何事件
        //制定你这个管理员将来关注哪个事件
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);

        while (true) {
            //解决空转  没事件则休息 阻塞， 有事件运行
            selector.select();
            //4。处理事件
            //selectionKeys 内部包含所有发生的事件 set集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                System.out.println("SelectionKey:" + key);
//                SelectableChannel channel = key.channel();
                ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                channel.accept();//建立连接
                System.out.println("ServerSocketChannel:" + channel);
            }
        }
    }
}
